package com.yinuo.controller;

import com.alibaba.fastjson.JSON;
import com.yinuo.common.DateUtil;
import com.yinuo.common.JsonResult;
import com.yinuo.common.UUIDUtil;
import com.yinuo.entity.DocBinary;
import com.yinuo.entity.GlobalContext;
import com.yinuo.entity.LinuxShellCmd;
import com.yinuo.entity.PageJson;
import com.yinuo.repository.DocRepository;
import com.yinuo.repository.LinuxRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.util.*;

/**
 * Created by Administrator on 2018/7/16.
 */
@Controller
@RequestMapping("documents")
public class DocController {
    private static Logger logger = LoggerFactory.getLogger(DocController.class);

    @Autowired
    private DocRepository docRepository;

    @RequestMapping("docSave")
    @ResponseBody
    public String saveDoc(String htmlContent,String title,String docType){
        try {
            DocBinary bin = new DocBinary();
            bin.setDoc_id(UUIDUtil.UUID32());
            bin.setDoc_type(docType);
            bin.setAuthor("佚名");
            bin.setIntime(DateUtil.getFullDate());
            bin.setUpdateTime(DateUtil.getFullDate());
            bin.setRemark("");
            bin.setTitle(title);
            bin.setContent(htmlContent);
            docRepository.save(bin);
            return JsonResult.toSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.toFaild();
        }
    }

    private static Map<String, Object> objectToMap(Object obj){
        Map<String, Object> map = null;
        try {
            map = new HashMap<>();
            Class<?> clazz = obj.getClass();
            System.out.println(clazz);
            for (Field field : clazz.getDeclaredFields()) {
                field.setAccessible(true);
                String fieldName = field.getName();
                Object value = field.get(obj);
                if(value!=null)
                    map.put(fieldName, value);
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    @RequestMapping("docQuery")
    @ResponseBody
    public String linuxDocQuery(@RequestParam(defaultValue = "0") int curPage,
                                @RequestParam(defaultValue = "10")int pagesize,
                                DocBinary doc){
        Sort sort = new Sort(Sort.Direction.ASC,"intime");
        Page<DocBinary> p = null;
        try {
            p = docRepository.findAll(new Specification<DocBinary>() {
                @Override
                public Predicate toPredicate(Root<DocBinary> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                    List<Predicate> predicateList = new ArrayList<>();
                    Predicate p1 = criteriaBuilder.like(root.get("doc_id").as(String.class), "%" + doc.getDoc_id() + "%");
                    Predicate p2 = criteriaBuilder.like(root.get("author").as(String.class), "%" + doc.getAuthor() + "%");
                    Predicate p3 = criteriaBuilder.like(root.get("title").as(String.class), "%" + doc.getTitle() + "%");
                    Predicate p4 = criteriaBuilder.equal(root.get("doc_type").as(String.class),doc.getDoc_type());
                    if(StringUtils.isEmpty(doc.getDoc_id())&&
                        StringUtils.isEmpty(doc.getAuthor())&&
                        StringUtils.isEmpty(doc.getTitle())
                       ){
                        predicateList.add(p4);
                    }else{
                        Predicate p5 = criteriaBuilder.or(p1,p2,p3);
                        predicateList.add(criteriaBuilder.and(p5,p4));
                    }
                     Predicate[] pre = new Predicate[predicateList.size()];
                    return criteriaQuery.where(predicateList.toArray(pre)).getRestriction();
                }
            }, PageRequest.of(curPage,pagesize,sort));
        } catch (Exception e) {
            e.printStackTrace();
        }
        PageJson<DocBinary> pj = new PageJson();
        pj.setTotal(p.getTotalElements());
        pj.setData(p.getContent());
        String json = JSON.toJSONString(pj);
        return json;
    }

    @RequestMapping("getArticelByID")
    @ResponseBody
    public String getArticelByDocId(String docId){
        Optional<DocBinary> l =  docRepository.findById(docId);
        DocBinary linuxDocBinary = l.get();
        byte[] b = linuxDocBinary.getContent();
        try {
            String content = new String(b,"utf-8");
            return content;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return "找不到该资源";
        }
    }

    @RequestMapping("docEdit")
    @ResponseBody
    @Transactional
    public String linuxDocEdit(DocBinary docBinary){
        try {
            docRepository.updateByDocId(docBinary.getDoc_id(),docBinary.getTitle(),DateUtil.getFullDate(),docBinary.getContent());
            return JsonResult.toSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.toFaild();
        }
    }

    @RequestMapping("docDel")
    @ResponseBody
    public String linuxDocDel(String docId){
        try {
            DocBinary docBinary = new DocBinary();
            docBinary.setDoc_id(docId);
            docRepository.delete(docBinary);
            return JsonResult.toSuccess("删除成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.toFaild("删除失败！");
        }
    }

}
